package tankproject;

import java.awt.*;
import java.io.*;
import javax.imageio.*;

class TankView {

    private Game game;
    private Tank tank;
    private Image body;
    private Image turret;
    private Point center = new Point(31, 37);

    public TankView(Game game, Tank tank) {
        this.game = game;
        this.tank = tank;

        initImages();
    }

    private void initImages() {
        body = getImage("tank_body.png");
        turret = getImage("tank_turret.png");
    }

    private Image getImage(String imageName) {
        try {
            return ImageIO.read(new File("images/"+imageName));
        } catch (IOException e) {e.printStackTrace();}
        return null;
    }

    public void paint(Graphics g) {
        paintBody(g.create());
        paintBullets(g.create());
        paintTurret(g.create());
        paintFuel(g.create());
    }

    private void paintBody(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Point rotatePoint = getRotatePoint();
        g2d.rotate(tank.getRotation(), rotatePoint.x, rotatePoint.y);
        g.drawImage(body, tank.getPosition().x, tank.getPosition().y, game);
    }

    private Point getRotatePoint() {
        return new Point(tank.getPosition().x + center.x,
                tank.getPosition().y + center.y);
    }

    private void paintTurret(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Point rotatePoint = getRotatePoint();
        Point mouse = game.getMouseOrZeroPoint();
        double rotation = Math.atan2(mouse.y - rotatePoint.y,
                mouse.x - rotatePoint.x);

        g2d.rotate(rotation, rotatePoint.x, rotatePoint.y);
        g.drawImage(turret, tank.getPosition().x, tank.getPosition().y, game);
    }

    private void paintFuel(Graphics g) {
        g.drawRect(20, 500, 200, 30);
        g.setColor(Color.GREEN);
        g.fillRect(21, 501, (int)(tank.percentFuelRemaining() * 199), 29);
        g.setColor(Color.BLACK);
        g.drawString("Fuel", 100, 520);
    }

    private void paintBullets(Graphics g) {
        for (Object o : tank.getBullets()) {
            Bullet b = (Bullet)o;
            b.paint(g.create());
        }
    }

}
